package com.itheima;

import org.apache.commons.io.IOUtils;
import sun.nio.ch.IOUtil;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@WebServlet("/DownloadStudent")
public class DownloadStudent extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //测试数据共享
       /* Object name = request.getAttribute("username");
        System.out.println("我获取了username=" + name);*/


        //下载
        //获取文件的路径
        //让浏览器响应为下载
        //读取文件



        //获取要下载的文件名
        response.setContentType(getServletContext().getMimeType("stu.txt"));
      /*
      设置响应头以下载方式打开附件
      Content-Disposition  处理形式
      attachment附件进行处理 filename指定下载之后的文件名称
       */
      response.setHeader("Content-Disposition","attachment;filename=stu.txt");

      //获取绝对路径
        //D:\IdeaProjects\JavaWeb\day05_Student\web\aa\stu.txt
        String realPath = getServletContext().getRealPath("/aa/stu.txt");
        //System.out.println(realPath);

        //创建输入流把文件路径放进去
        InputStream is = new FileInputStream(realPath);
        //获取输出流
        OutputStream os = response.getOutputStream();
        byte[] b = new byte[1024];
        int a;
        //循环读取
        while ((a=is.read(b))!=-1){
            os.write(b,0,a);
        }
        is.close();
        os.close();

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
